// 常量定义（可配置）
var DAILY_RETENTION_DAYS = 1;    // 保留当天数据
var WEEKLY_RETENTION_DAYS = 7;    // 保留7天数据
var MONTHLY_RETENTION_DAYS = 30;  // 保留30天数据
var YEARLY_RETENTION_MONTHS = 12; // 保留12个月数据

// 工具函数：获取ISO周数
function getWeekKey(date) {
    var d = new Date(date);
    d.setHours(0, 0, 0, 0);
    d.setDate(d.getDate() + 3 - (d.getDay() + 6) % 7);
    var week1 = new Date(d.getFullYear(), 0, 4);
    week1.setHours(0, 0, 0, 0);
    var weekNum = Math.floor((d.getTime() - week1.getTime()) / (7 * 24 * 60 * 60 * 1000)) + 1;
    
    if (weekNum < 1) return (d.getFullYear() - 1) + "-W52";
    if (weekNum > 52) {
        var testDate = new Date(week1);
        testDate.setDate(week1.getDate() + 52 * 7);
        if (d >= testDate) return d.getFullYear() + "-W53";
    }
    return d.getFullYear() + "-W" + weekNum.toString().padStart(2, "0");
}

// 初始化数据结构
var initStats = {
    byTimeDimension: {
        hourly: {},  // 原始数据（由其他流程填充）
        daily: {},    // 格式: {"2025-06-09": {"pointId": value}}
        weekly: {},   // 格式: {"2025-W24": {"2025-06-09": {"pointId": value}}}
        monthly: {},  // 格式: {"2025-06": {"2025-06-09": {"pointId": value}}}
        yearly: {}     // 格式: {"2025": {"2025-06": {"pointId": value}}}
    },
    lastUpdated: null
};

// 主聚合流程
var currentDate = new Date();
var stats = global.get('_STATISTICS_') || { byTimeDimension: {} };

// 当前时间键
var currentDay = currentDate.toISOString().slice(0, 10);
var currentWeek = getWeekKey(currentDate);
var currentMonth = currentDate.toISOString().slice(0, 7);
var currentYear = currentDate.getFullYear().toString();

// 1. 初始化数据结构（修复关键点）
function initDimension(dimension, key) {
    stats.byTimeDimension[dimension] = stats.byTimeDimension[dimension] || {};
    stats.byTimeDimension[dimension][key] = stats.byTimeDimension[dimension][key] || {};
}

// 2. 更新daily维度（当天累计）
initDimension('daily', currentDay);
let dailyStats = {}; // 重置为新对象，避免累加到之前的数据上

// 遍历所有小时数据进行累加
Object.keys(stats.byTimeDimension.hourly || {}).forEach(function(hourKey) {
    if (hourKey.startsWith(currentDay.replace(/-/g, '-'))) {
        var hourData = stats.byTimeDimension.hourly[hourKey];
        Object.keys(hourData).forEach(function(pointId) {
            if (!dailyStats[pointId]) {
                dailyStats[pointId] = 0;
            }
            // 直接使用hourly中累计的sum
            dailyStats[pointId] = Number((dailyStats[pointId] + hourData[pointId].stats.sum).toFixed(2));
        });
    }
});

// 更新daily维度
stats.byTimeDimension.daily[currentDay] = dailyStats;

// 3. 更新weekly维度（最近7天）
// 保留现有的weekly数据
let existingWeekly = stats.byTimeDimension.weekly || {};
stats.byTimeDimension.weekly = existingWeekly;

for (let i = 0; i < WEEKLY_RETENTION_DAYS; i++) {
    let date = new Date(currentDate);
    date.setDate(date.getDate() - i);
    let dayKey = date.toISOString().slice(0, 10);
    
    // 如果是当天，使用新计算的数据
    if (dayKey === currentDay) {
        stats.byTimeDimension.weekly[dayKey] = dailyStats;
        continue;
    }
    
    // 否则保留现有数据
    if (!stats.byTimeDimension.weekly[dayKey]) {
        stats.byTimeDimension.weekly[dayKey] = {};
        // 只对没有的日期从hourly数据中计算
        let dayStats = {};
        Object.keys(stats.byTimeDimension.hourly || {}).forEach(function(hourKey) {
            if (hourKey.startsWith(dayKey.replace(/-/g, '-'))) {
                var hourData = stats.byTimeDimension.hourly[hourKey];
                Object.keys(hourData).forEach(function(pointId) {
                    if (!dayStats[pointId]) {
                        dayStats[pointId] = 0;
                    }
                    dayStats[pointId] = Number((dayStats[pointId] + hourData[pointId].stats.sum).toFixed(2));
                });
            }
        });
        stats.byTimeDimension.weekly[dayKey] = dayStats;
    }
}

// 4. 更新monthly维度（最近30天）
// 保留现有的monthly数据
let existingMonthly = stats.byTimeDimension.monthly || {};
stats.byTimeDimension.monthly = existingMonthly;

for (let i = 0; i < MONTHLY_RETENTION_DAYS; i++) {
    let date = new Date(currentDate);
    date.setDate(date.getDate() - i);
    let dayKey = date.toISOString().slice(0, 10);
    
    // 如果是当天，使用新计算的数据
    if (dayKey === currentDay) {
        stats.byTimeDimension.monthly[dayKey] = dailyStats;
        continue;
    }
    
    // 否则保留现有数据
    if (!stats.byTimeDimension.monthly[dayKey]) {
        stats.byTimeDimension.monthly[dayKey] = {};
        // 只对没有的日期从hourly数据中计算
        let dayStats = {};
        Object.keys(stats.byTimeDimension.hourly || {}).forEach(function(hourKey) {
            if (hourKey.startsWith(dayKey.replace(/-/g, '-'))) {
                var hourData = stats.byTimeDimension.hourly[hourKey];
                Object.keys(hourData).forEach(function(pointId) {
                    if (!dayStats[pointId]) {
                        dayStats[pointId] = 0;
                    }
                    dayStats[pointId] = Number((dayStats[pointId] + hourData[pointId].stats.sum).toFixed(2));
                });
            }
        });
        stats.byTimeDimension.monthly[dayKey] = dayStats;
    }
}

// 5. 更新yearly维度（最近12个月）
// 保留现有的yearly数据
let existingYearly = stats.byTimeDimension.yearly || {};
stats.byTimeDimension.yearly = existingYearly;

for (let i = 0; i < YEARLY_RETENTION_MONTHS; i++) {
    let date = new Date(currentDate);
    date.setMonth(date.getMonth() - i);
    let monthKey = date.toISOString().slice(0, 7);
    
    // 如果是当月，重新计算
    if (monthKey === currentMonth) {
        let monthStats = {};
        Object.keys(stats.byTimeDimension.hourly || {}).forEach(function(hourKey) {
            if (hourKey.startsWith(monthKey)) {
                var hourData = stats.byTimeDimension.hourly[hourKey];
                Object.keys(hourData).forEach(function(pointId) {
                    if (!monthStats[pointId]) {
                        monthStats[pointId] = 0;
                    }
                    monthStats[pointId] = Number((monthStats[pointId] + hourData[pointId].stats.sum).toFixed(2));
                });
            }
        });
        stats.byTimeDimension.yearly[monthKey] = monthStats;
        continue;
    }
    
    // 否则保留现有数据
    if (!stats.byTimeDimension.yearly[monthKey]) {
        stats.byTimeDimension.yearly[monthKey] = {};
    }
}

// 6. 数据清理（保留周期）
function cleanData() {
    // daily保留当天
    let dailyData = {};
    for (let i = 0; i < DAILY_RETENTION_DAYS; i++) {
        let date = new Date(currentDate);
        date.setDate(date.getDate() - i);
        let dayKey = date.toISOString().slice(0, 10);
        if (stats.byTimeDimension.daily[dayKey]) {
            dailyData[dayKey] = stats.byTimeDimension.daily[dayKey];
        }
    }
    stats.byTimeDimension.daily = dailyData;
    
    // weekly保留最近7天
    let weeklyData = {};
    for (let i = 0; i < WEEKLY_RETENTION_DAYS; i++) {
        let date = new Date(currentDate);
        date.setDate(date.getDate() - i);
        let dayKey = date.toISOString().slice(0, 10);
        weeklyData[dayKey] = stats.byTimeDimension.weekly[dayKey] || {};
    }
    stats.byTimeDimension.weekly = weeklyData;
    
    // monthly保留最近30天
    let monthlyData = {};
    for (let i = 0; i < MONTHLY_RETENTION_DAYS; i++) {
        let date = new Date(currentDate);
        date.setDate(date.getDate() - i);
        let dayKey = date.toISOString().slice(0, 10);
        monthlyData[dayKey] = stats.byTimeDimension.monthly[dayKey] || {};
    }
    stats.byTimeDimension.monthly = monthlyData;
    
    // yearly保留最近12个月
    let yearlyData = {};
    for (let i = 0; i < YEARLY_RETENTION_MONTHS; i++) {
        let date = new Date(currentDate);
        date.setMonth(date.getMonth() - i);
        let monthKey = date.toISOString().slice(0, 7);
        yearlyData[monthKey] = stats.byTimeDimension.yearly[monthKey] || {};
    }
    stats.byTimeDimension.yearly = yearlyData;
}
cleanData();

// 保存结果
global.set('_STATISTICS_', stats);

return msg